// Copyright (C) 2020-2022 Intel Corporation
//
// SPDX-License-Identifier: MIT

import React from 'react';
import { Row, Col } from 'antd/lib/grid';
import Text from 'antd/lib/typography/Text';
import Icon, { LockFilled, UnlockOutlined, EyeInvisibleFilled, EyeOutlined } from '@ant-design/icons';

import CVATTooltip from 'components/common/cvat-tooltip';
import { Collapse, Tag, Button } from 'antd';
import { ArrowIcon, CopyAttributeIcon, EyeCloseIcon, EyeIcon, LockIcon, UnlockIcon } from 'icons';
import { useDispatch, useSelector } from 'react-redux';
import { CombinedState } from 'reducers';
import { copyLabelAttributes, resetCopyLabelAttributes } from 'actions/annotation-actions';
import useAnnotation from 'hooks/useAnnotation';
import LabelKeySelectorPopover from './label-key-selector-popover';

interface Props {
    labelName: string;
    labelColor: string;
    attributes: any[];
    labelID: number;
    visible: boolean;
    statesHidden: boolean;
    statesLocked: boolean;
    keyToLabelMapping: Record<string, number>;
    labelIndex: number;
    hideStates(): void;
    showStates(): void;
    lockStates(): void;
    unlockStates(): void;
    updateLabelShortcutKey(updatedKey: string, labelID: number): void;
}

function LabelItemComponent(props: Props): JSX.Element {
    const {
        labelName,
        labelColor,
        labelID,
        keyToLabelMapping,
        visible,
        statesHidden,
        statesLocked,
        attributes,
        labelIndex,
        hideStates,
        showStates,
        lockStates,
        unlockStates,
        updateLabelShortcutKey,
    } = props;
    const dispatch = useDispatch();
    const copyLabelId = useSelector((state: CombinedState) => state.annotation.drawing.copyLabelId);
    const { readonly } = useAnnotation();

    // create reversed mapping just to receive key easily
    const labelToKeyMapping: Record<string, string> = Object.fromEntries(
        Object.entries(keyToLabelMapping).map(([key, _labelID]) => [_labelID, key]),
    );
    const labelShortcutKey = labelToKeyMapping[labelID] || '?';
    const classes = {
        lock: {
            enabled: { className: 'cvat-label-item-button-lock cvat-label-item-button-lock-enabled' },
            disabled: { className: 'cvat-label-item-button-lock' },
        },
        hidden: {
            enabled: { className: 'cvat-label-item-button-hidden cvat-label-item-button-hidden-enabled' },
            disabled: { className: 'cvat-label-item-button-hidden' },
        },
    };

    const labelItems = attributes.map((attribute: any, index: number) => (
        <div key={index}>
            <span className='mr-2 text-[#86909C]'>{attribute.name}:</span>
            <span>{Array.isArray(attribute.values) ? attribute.values.join('；') : attribute.values}</span>
        </div>
    ));

    /**
     * 复制标签
     */
    const toggleCopy = () => {
        if (copyLabelId !== labelID) {
            dispatch(copyLabelAttributes(labelID));
        } else {
            dispatch(resetCopyLabelAttributes());
        }
    };

    return (
        <div>
            <Collapse
                ghost
                expandIconPosition='end'
                expandIcon={({ isActive }) => (
                    <Icon component={ArrowIcon} className={isActive ? 'rotate-0' : 'rotate-180'} />
                )}
                items={[
                    {
                        label: (
                            <div>
                                <Tag color={labelColor}>{labelIndex + 1}</Tag>
                                <span className='font-bold text-base'>{labelName}</span>
                            </div>
                        ),
                        key: labelID,
                        children: (
                            <div>
                                <div className='rounded bg-[#F7F8FA] p-3 space-y-3'>{labelItems}</div>
                            </div>
                        ),
                    },
                ]}
            />
            <div className='flex items-center justify-around gap-2 p-3'>
                <div className='flex-shrink-0'>
                    {statesLocked ? (
                        // <LockFilled {...classes.lock.enabled} onClick={unlockStates} />
                        <Icon component={LockIcon} {...classes.lock.enabled} onClick={unlockStates} />
                    ) : (
                        // <UnlockOutlined {...classes.lock.disabled} onClick={lockStates} />
                        <Icon component={UnlockIcon} {...classes.lock.disabled} onClick={lockStates} />
                    )}
                </div>
                <div className='flex-1 flex justify-center items-center'>
                    {statesHidden ? (
                        // <EyeInvisibleFilled {...classes.hidden.enabled} onClick={showStates} />
                        <Icon component={EyeCloseIcon} {...classes.hidden.enabled} onClick={showStates} />
                    ) : (
                        // <EyeOutlined {...classes.hidden.disabled} onClick={hideStates} />
                        <Icon component={EyeIcon} {...classes.hidden.disabled} onClick={hideStates} />
                    )}
                </div>
                {!readonly && (
                    <div className='flex-shrink-0'>
                        <CVATTooltip title='Copy attributes'>
                            <span
                                className={
                                    labelID === copyLabelId ? '!text-[#165DFF] p-6px bg-[#F7F8FA] rounded-2px' : 'p-6px'
                                }
                            >
                                <Icon component={CopyAttributeIcon} onClick={toggleCopy} />
                            </span>
                        </CVATTooltip>
                    </div>
                )}
            </div>
        </div>
    );

    return (
        <Row
            align='stretch'
            justify='space-around'
            className={[
                'cvat-objects-sidebar-label-item',
                visible ? '' : 'cvat-objects-sidebar-label-item-disabled',
            ].join(' ')}
        >
            <Col span={2}>
                <div style={{ background: labelColor }} className='cvat-label-item-color'>
                    {' '}
                </div>
            </Col>
            <Col span={12}>
                <CVATTooltip title={labelName}>
                    <Text strong className='cvat-text'>
                        {labelName}
                    </Text>
                </CVATTooltip>
            </Col>
            <Col span={3}>
                <LabelKeySelectorPopover
                    keyToLabelMapping={keyToLabelMapping}
                    labelID={labelID}
                    updateLabelShortcutKey={updateLabelShortcutKey}
                >
                    <Button className='cvat-label-item-setup-shortcut-button' size='small' ghost type='dashed'>
                        {labelShortcutKey}
                    </Button>
                </LabelKeySelectorPopover>
            </Col>
            <Col span={2} offset={1}>
                {statesLocked ? (
                    <LockFilled {...classes.lock.enabled} onClick={unlockStates} />
                ) : (
                    <UnlockOutlined {...classes.lock.disabled} onClick={lockStates} />
                )}
            </Col>
            <Col span={3}>
                {statesHidden ? (
                    <EyeInvisibleFilled {...classes.hidden.enabled} onClick={showStates} />
                ) : (
                    <EyeOutlined {...classes.hidden.disabled} onClick={hideStates} />
                )}
            </Col>
        </Row>
    );
}

export default React.memo(LabelItemComponent);
